﻿// --------------------------------
// <copyright file="NetPlayer.cs" company="Faculty of Information Technology, Czech Technical University in Prague">
//     This document is shared by Microsoft Public License (MS-PL)
//     For further details please see http://msdn.microsoft.com/en-us/library/ff648068.aspx or license.txt.
// </copyright>
// <author>Lukáš Molnár</author>

// <email>molnaluk@fit.cvut.cz</email>

// <date>31. 3. 2012 13:00:27</date>

// <summary>
// 
// </summary>
// --------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LProject.Phone.Net;
using FITClub.Episode1.Components;
using Microsoft.Xna.Framework;

namespace FITClub.Episode1.Controller.Net
{
    /// <summary>
    /// Network player.
    /// </summary>
    public class NetPlayer : APlayer
    {
        public byte ID { get; private set; }

        protected APlayer local;
        protected MulticastClient client;
        protected DateTime lastPacketTime;
        protected int receiveSequnece;
        protected PlayableCharacter character;
        public Vector2 DesiredPosition;

        public NetPlayer(string name, byte ID, APlayer local, MulticastClient client, PlayableCharacter character)
            : base(name)
        {
            this.ID = ID;
            this.receiveSequnece = 0;
            this.local = local;
            this.client = client;
            this.character = character;
        }

        /// <summary>
        /// Processes packet containing controller state.
        /// </summary>
        /// <param name="packet"></param>
        public void Update(IMulticastPacket packet)
        {
            int seq = packet.GetInt32(RawPacket.HeaderLength + 1);
            if (seq > this.receiveSequnece)
            {
                this.receiveSequnece = seq;
                this.lastPacketTime = DateTime.Now;
                this.last = this.actual;
                this.actual = new VirtualGamepadState(new byte[] { packet.Data[RawPacket.HeaderLength] });
                //////if (packet.SenderID != this.client.MyID)
                //////{
                //////    DesiredPosition = new Vector2(packet.GetSingle(RawPacket.HeaderLength + 5), packet.GetSingle(RawPacket.HeaderLength + 9));
                //////    character.SetState(DesiredPosition, seq);
                //////}
            }
        }

        /// <summary>
        /// Updates controller state.
        /// </summary>
        public override void Update()
        {
            this.local.Update();

            if ((DateTime.Now - lastPacketTime).TotalSeconds > 1.5)
            {
                this.actual = VirtualGamepadState.Default;
            }
        }



        public override void Dispose()
        {
            local.Dispose();
        }
    }
}